<?php
/**
 * 在线问诊类文件
 * 作者：刘单风
 * 最后修改时间：2018-12-03
 * 版权：医库PHP小组
 */

namespace app\model;
use MoCommon\DataState\CollectLogStatus;
use MoCommon\DataState\MoneyFlowType;
use MoCommon\DataState\QuestionLogStatus;
use MoCommon\DataState\TradeLogPayIssueStatus;
use MoCommon\Support\Helper;
use think\Model;
use think\Db;

class Members extends Model
{
    /**
     * 问答数统计
     *
     * @param array $parameters
     * @param bool
     * @param string 条件
     *
     * @return array
     *
     * @farwish
     */
    public function answerStatistic($parameters = null, $where = '')
    {
        $start = ($parameters['page'] - 1) * $parameters['limit'];
        $limit = $parameters['limit'] ? " limit $start,{$parameters['limit']}" : "";
        $where = $where ? " WHERE isdel=0 AND " . $where : " WHERE isdel=0";
        $sql = "SELECT answer_role_id, count(id) AS answer_num FROM appname_zhaoyisheng_wenda_log {$where} group by answer_role_id order by answer_num DESC" . $limit;
        $data = Db::query($sql);
        return $data;
    }

    /**
     * 条件查询用户信息.
     *
     * nickname 是微信用户名.
     *
     * @param string $where
     * @param bool $change_key 是否将键更改为id
     * @param array $parameters  其它组合条件
     *
     * @return array
     *
     * @farwish
     */
    public function necessInfoByWhere($where = '', $change_key = false)
    {
        $columns = "id, openid,unionid, name as true_name, nickname as name, headimg, administrative, zhicheng, isrenzheng, hospital, description, k_money, money, cost, cash_income, k_income, total_income,total_reward,total_kmoney,is_black,is_admin,question_price,invite_member_id,invite_status,free_convert_times,new_pay_to_see_msg,new_question_msg,new_question_append_msg,new_question_accept_msg,city,tag,answer_num,question_num,addtime,yiku_id,question_price,depid,question_kprice";
        $sql = "SELECT $columns FROM appname_m_members WHERE $where";
        $data = Db::query($sql);
        if ($data) {
            foreach ($data as &$val) {
                if ($val['isrenzheng'] < 0) {
                    $val['administrative'] = '';
                    $val['zhicheng'] = '';
                    $val['hospital'] = '';
                    $val['description'] = '';
                }
            }
            unset($val);
        }
        return $change_key ? Helper::array_column_combine($data, 'id') : $data;
    }

    /**
     * 被采纳数.
     *
     * @param array $role_ids
     * @return array
     *
     * @farwish
     */
    public function adoptCount(array $role_ids)
    {
        $condition = "accept_time <> 0 AND " . Helper::join_condition($role_ids, 'answer_role_id');

        $sql = "SELECT answer_role_id, count(accept_time) AS adopt_count FROM `appname_zhaoyisheng_wenda_log` WHERE {$condition} group by answer_role_id;";

        $res = Db::query($sql);

        return Helper::array_column_combine($res, 'answer_role_id');
    }

    /**
     * 当前用户是否已关注.
     *
     * @param array 条件
     * @param int 当前用户id
     * @param bool 是否改变key
     *
     * @return array
     *
     * @farwish
     */
    public function findUserCollect(array $role_ids, $user_id, $change_key = false)
    {
        $where = "status = " . CollectLogStatus::YES . " AND " . Helper::join_condition($role_ids, 'collect_role_id') . " AND role_id = '{$user_id}'";

        $array = Db::table('appname_zhaoyisheng_collect_log')
            ->field('role_id, collect_role_id, status')
            ->where($where)
            ->select();
        return $change_key ? Helper::array_column_combine($array, 'collect_role_id') : $array;
    }

    //获取订单信息
    public function findTrade($where,$column="")
    {
        if($column){
            $data = Db::table('appname_zhaoyisheng_trade_log')
                ->field($column)
                ->where($where)
                ->find();
        }else{
            $data = Db::table('appname_zhaoyisheng_trade_log')
                ->where($where)
                ->find();
        }

        return $data;
    }

    //获取成员的openid;datatype=1返回所有信息
    public function findMembers($where,$datatype=1)
    {
        if ($datatype) {
            $data = Db::table('appname_m_members')
                ->where($where)
                ->find();
        } else {
            $data = Db::table('appname_m_members')
                ->field('openid')
                ->where($where)
                ->value('openid');
        }

        return $data;
    }

    //保存订单信息
    public function insertTrade($data)
    {
        $returnid = Db::table('appname_zhaoyisheng_trade_log')
            ->insertGetId($data);
        return $returnid;
    }


    //保存提问信息
    public function insertAsk($data)
    {
        $returnid = Db::table('appname_zhaoyisheng_question_log')
            ->insertGetId($data);
        return $returnid;
    }

    //保存图片信息
    public function insertPics($data,$role_id,$question_id)
    {
        foreach ($data as $v) {
            $indata = [
                'site' => $v,
                'role_id' => $role_id,
                'question_id' => $question_id,
            ];
            Db::table('appname_zhaoyisheng_pic_log')
                ->insert($indata);
        }
    }

    //更新成员表信息
    public function updateMembers($data,$where)
    {
        Db::table('appname_m_members')
            ->where($where)
            ->update($data);
    }

    //用户提问总数
    public function countAsk($where)
    {
        $count = Db::table('appname_zhaoyisheng_question_log')
            ->where($where)
            ->count();
        return $count;
    }

    /**
     * 订单信息
     * @param $where
     * @param $feilds
     * @return
     */
    public function tradeClomn($where,$feilds)
    {
        $data=Db::table('appname_zhaoyisheng_trade_log')
            ->field($feilds)
            ->where($where)
            ->select();
        return $data;
    }

    /**
     * @param array $result
     *
     * @param string $uid_key
     *
     * @param string $output_key
     *
     * @param string $id
     *
     * @desc 附加用户信息
     */
    public function attachMember(array $result,$uid_key='uid',$output_key='member',$id='id')
    {
        $ids = array_column($result, $uid_key);
        $where = Helper::join_condition($ids, $id);
        $feilds = "id,nickname,name,name as true_name,headimg,administrative, zhicheng, isrenzheng, hospital, description";
        $obj = Db::table('appname_m_members')
            ->field($feilds)
            ->where($where)
            ->select();
        $user_list = $obj;

        if ($user_list) {
            foreach ($user_list as &$val) {
                if ($val['isrenzheng'] < 0) {
                    $val['administrative'] = '';
                    $val['zhicheng'] = '';
                    $val['hospital'] = '';
                    $val['describe'] = '';
                }
            }
            unset($val);
        }

        //用户数组
        if ($user_list) {
            foreach ($user_list as & $user) {
                $new_user_list[$user[$id]] = $user;
            }
            unset($user);
        }

        if ($result) {
            foreach ($result as & $v) {
                $v[$output_key] = isset($new_user_list[$v[$uid_key]]) ? $new_user_list[$v[$uid_key]] : [];
            }

            unset($v);
        }
        return $result;
    }

    /**
     * 回复的列表内容.
     *
     * @farwish
     */
    public function replys($where, $role_id)
    {
        //过滤被删除的评论
        $add_sql = ' isdel = 0';
        $where['conditions'] = empty($where['conditions'])?'': $where['conditions'];
        $where['conditions'] = Helper::build_where_sql($add_sql,'and',$where['conditions']);

        $data=Db::table('appname_zhaoyisheng_wenda_log')
            ->field("id, is_anonymous,content, parent_id, answer_role_id, dianzannum,question_type,is_open,invite_uid,type, path, sort, FROM_UNIXTIME(addtime, '%m-%d %H:%i') AS create_time, accept_time")
            ->where($where['conditions'])
            ->order("accept_time DESC")
            ->select();

        // 图片信息
        $answer_ids = array_column($data, 'id');
        $where = Helper::join_condition($answer_ids, 'answer_id');

        $pics=Db::table('appname_zhaoyisheng_pic_log')
            ->field('site, content, pic_status, question_id, answer_id, FROM_UNIXTIME(addtime) AS create_time')
            ->where($where)
            ->select();
        $new_pics = [];
        if ($pics) {
            $website = Config::get('app.website');
            foreach ($pics as &$val) {
                $val['site'] = $website['imgurl'] . $val['site'];
                $new_pics[$val['answer_id']][] = $val;
            }
            unset($val, $pics);
        }

        // 用户信息
        $role_ids = array_column($data, 'answer_role_id');
        $members=$this->necessInfoByWhere(Helper::join_condition($role_ids, 'id'),true);
        $flag_id = null;
        $new_tmp_data = $not_accept_reply_data = [];
        $new_tmp_contain = [];

        if ($data) {
            $answer_ids = array_column($data, 'id');
            foreach ($data as $k => &$val) {
                // 过滤第一屏错乱数据
                if ( !empty($where['offset']) && $val['parent_id'] && ! in_array($val['parent_id'], $answer_ids) ) {
                    unset($data[$k]);
                    continue;
                }

                $val['accept_time'] = $val['accept_time'] ? date('m-d H:i', $val['accept_time']) : 0;

                if ($val['accept_time']) {
                    $flag_id = $val['id'];
                }

                $val['pic'] = isset($new_pics[$val['id']]) ? $new_pics[$val['id']] : [];
                $val['member_info'] = isset($members[$val['answer_role_id']]) ? $members[$val['answer_role_id']] : [];

                // 引入分页机制后, 要知道是对哪个回答者的回复.
                $val['reply_who'] = '';

                if ($val['parent_id']) {
                    $answer_role_obj=Db::table('appname_zhaoyisheng_wenda_log')
                        ->field('answer_role_id')
                        ->where("id = '{$val['parent_id']}'")
                        ->value('answer_role_id');

                    $answer_role_id = $answer_role_obj ? $answer_role_obj : '';

                    $member_obj=Db::table('appname_m_members')
                        ->field('name')
                        ->where("id = '{$answer_role_id}'")
                        ->value('name');
                    $val['reply_who'] = $member_obj ? $member_obj : '';
                }

                if ( isset($flag_id) && ($val['id'] != $flag_id) && ($val['parent_id'] != $flag_id) && (! in_array($val['parent_id'], $new_tmp_contain)) ) {
                    // 有采纳, 其余数据
                    $not_accept_reply_data[] = $val;
                } else {
                    $new_tmp_contain[] = $val['id'];
                    // 采纳数据
                    $new_tmp_data[] = $val;
                }
            }
        }

        $sign = 0;
        if ( empty($not_accept_reply_data) ) {
            $sign = 1;
            // 没有采纳的情况
            $not_accept_reply_data = $new_tmp_data;
        }

        // 对剩余按sort排序

        $need_sorted_id = [];

        foreach ($not_accept_reply_data as $k => $v) {

            if ( ($v['parent_id'] == 0) && ($v['sort'] > 0) ) {

                // 一级排序, 跟在它后面的parent=0的跟在其后
                $need_sorted_id[$v['id']] = $v['sort'];
            }
        }

        $final_not_accept_data = $final_not_accept_data_else = [];

        if ($need_sorted_id) {

            uasort($need_sorted_id, function($a, $b) {
                if ($a == $b) return 0;
                return ($a < $b) ? 1 : -1;
            });

            foreach ($need_sorted_id as $key => $value) {

                $flag = false;
                $contain = [];

                foreach ($not_accept_reply_data as $k => $v) {
                    if ( ($key == $v['id']) ) {
                        $flag = true;
                        $contain[] = $v['id'];
                        $final_not_accept_data[] = $v;
                    }

                    if ($flag && ($v['parent_id'] != 0) ) {
                        if ( in_array($v['parent_id'], $contain) ) {
                            $final_not_accept_data[] = $v;
                            $contain[] = $v['id'];
                        } else {
                            continue;
                        }
                    }

                }
            }

            // 与上面需要排序的分开处理  11-30 00:00:00 fixed 2/2.
            $final_not_accept_data_ids = array_column($final_not_accept_data, 'id');
            foreach ($not_accept_reply_data as $k => $v) {
                if (! in_array($v['id'], $final_not_accept_data_ids) && ! array_key_exists($v['id'],           $final_not_accept_data_else) ) {
                    $final_not_accept_data_else[$v['id']] = $v;
                }
            }
        } else {
            $final_not_accept_data = $not_accept_reply_data;
        }

        $final_not_accept_data_ids = array_column($final_not_accept_data, 'id');
        if ($final_not_accept_data_else) {
            // 因为 $not_accept_reply_data 的顺序不定
            foreach ($final_not_accept_data_else as $else_k => $else_v) {
                if (in_array($else_v['id'], $final_not_accept_data_ids) ) {
                    unset($final_not_accept_data_else[$else_k]);
                }
            }
        }

        if ($sign) {
            $data = $final_not_accept_data;
            $sort_ids = array_column($final_not_accept_data, 'id');

            foreach ($new_tmp_data as $value) {
                if (! in_array($value['id'], $sort_ids) ) {
                    array_push($data, $value);
                }
            }
        } else {
            $data = array_merge($new_tmp_data, $final_not_accept_data, $final_not_accept_data_else);
        }

        // 保证返回索引数组, 前端用数组.
        $replys= array_values($data);


        if ($replys) {
            $flag = 0;
            $flag_s = 0;
            foreach ($replys as $k => &$val) {
                if ($k == 0) {
                    $flag = $val['id'];
                }
                if ( ($k > 0) && ($val['parent_id'] == 0) ) {
                    $flag_s = $val['id'];
                }
                if ( ($k == 0) || empty($flag_s) ) {
                    $val['the_first_group'] = 1;
                }
            }
        }

        return $replys;
    }

    /**
     * 增加浏览量.
     *
     * @param int $question_id
     *
     * @return bool
     *
     * @farwish
     */
    public function increaseShownum($question_id)
    {
        $sql = "UPDATE appname_zhaoyisheng_question_log set shownum = shownum+1 WHERE question_id = {$question_id}";
        $res = Db::query($sql);
    }

    //查询问题信息
    public function findQuestion($where)
    {
        $data = Db::table('appname_zhaoyisheng_question_log')
            ->where($where)
            ->find();
        return $data;
    }

    //查询问题回复信息
    public function findWenda($where,$column="")
    {
        if($column){
            $data = Db::table('appname_zhaoyisheng_wenda_log')
                ->field($column)
                ->where($where)
                ->find();
        }else{
            $data = Db::table('appname_zhaoyisheng_wenda_log')
                ->where($where)
                ->find();
        }

        return $data;
    }
    //问答总数
    public function countWenda($where)
    {
        $data = Db::table('appname_zhaoyisheng_wenda_log')
        ->where($where)
        ->count();
        return $data;

    }

    /**
     * 问题回复.
     *
     * @param array $data
     *
     * @return int
     *
     * @farwish
     */
    public function reply($data)
    {
        $iddata = Db::table('appname_zhaoyisheng_wenda_log')
            ->insertGetId($data);
        return $iddata;
    }

    /**
     * 增加回复数, 未查看数.
     *
     * @param int $question_id
     * @return bool
     *
     * @farwish
     */
    public function increaseAnswernum($question_id)
    {
        $count = self::countWenda("question_id = $question_id AND isdel = 0 AND parent_id = 0");

        $sql = "UPDATE appname_zhaoyisheng_question_log SET answer_num = $count, hint_num = hint_num + 1 WHERE question_id = '{$question_id}'";
        $res = Db::query($sql);
    }

    /**
     * 增加回答的未查看回复数.
     *
     * @param int $answer_id
     *
     * @return void
     *
     * @farwish
     */
    public function increaseHintnum($answer_id)
    {
        $sql = "UPDATE appname_zhaoyisheng_wenda_log set reply_hint_num = reply_hint_num + 1 WHERE id = {$answer_id}";

        $res = Db::query($sql);
    }

    /**
     * 达追问上限自动完成.
     *
     * 在病人已追问2次，医生回复后.
     * 患者有两次追问， 医生回答了parent_id=0的两次不同追问，自动结束
     *
     * @param int $question_id      问题id
     * @param int $role_id          提问者id
     * @param int $answer_role_id   回答者id
     * @param int $trade_id         订单id
     *
     * @return bool
     *
     * @farwish
     */
    public function checkAutoFinish($question_id, $role_id, $answer_role_id, $trade_id)
    {
        $cond = "question_id = '{$question_id}' AND answer_role_id = '{$role_id}'";

        $wdcount=self::countWenda($cond);
        if ($wdcount >= 2) {

            $trade_res=self::findTrade("id = '{$trade_id}'","price, to_uid");

            if ($trade_res) {

                $reply_cond = "question_id = '{$question_id}' AND answer_role_id = '{$trade_res->to_uid}' AND parent_id !=0";

                $recount = Db::table('appname_zhaoyisheng_wenda_log')
                    ->distinct("parent_id")
                    ->where($reply_cond)
                    ->count();

                if ( $recount >= 2 ) {
                    Db::startTrans();
                    $bool=Db::table('appname_zhaoyisheng_trade_log')
                        ->where("id = '{$trade_id}'")
                        ->update(['pay_issue_status' => TradeLogPayIssueStatus::FINISH]);

                    Db::table('appname_zhaoyisheng_question_log')
                        ->where('question_id='.$question_id)
                        ->update(['status' => QuestionLogStatus::FINISH]);

                    if (! $bool) {
                        Db::rollback();
                        return false;
                    }
                    // 金额给医生
                    $model=self::findMembers("id = '{$trade_res['to_uid']}'",1);
self::updateMembers([
    "money" => $model['money'] + $trade_res['price'],
    "cash_income" => $model['cash_income'] + $trade_res['price'],
    "total_income" => $model['total_income'] + $trade_res['price'],
],"id=".$model['id']);

                    $plus_bool = MMmodel::updateOne($model['id'], [
                        "money" => $model['money'] + $trade_res['price'],
                        "cash_income" => $model['cash_income'] + $trade_res['price'],
                        "total_income" => $model['total_income'] + $trade_res['price'],
                    ]);

                    if (! $plus_bool) {
                        Db::rollback();
                        return false;
                    }else{
                        // 流水
                        Db::table('appname_money_flow')
                            ->insert([
                                'uid' => $model['id'],
                                'money' => $model['money'],
                                'income' => $trade_res['price'],
                                'balance' => $model['money'] + $trade_res['price'],
                                'type' =>MoneyFlowType::RECEIVE_ONE_TO_ONE
                            ]);
                    }
                    Db::commit();
                    return true;
                }
            }
        }

        return false;
    }

    public function findDoctor($where)
    {
        $doctor = Db::table('appname_doctor')
            ->field("id,name,mobile_phone,hospital,dept_first,zhicheng,skill,description,member_id,renzheng,headimg")
            ->where($where)
            ->find();
        return $doctor;
    }
}